<%@ tag import="su.mvc.service.gui.MenuService" %>
<%@ tag import="su.mvc.service.gui.GuiService" %>
<%@ tag import="su.mvc.action.ActionSupport" %>
<%@ tag import="su.mvc.model.MenuItem" %>
<%@ tag import="java.io.IOException" %>
<%@ tag import="com.googlecode.objectify.Objectify" %>
<%@ tag import="org.apache.commons.lang.StringUtils" %>
<%@ tag language="java" pageEncoding="utf-8"  %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

<%!
    public void drawLink(String url, String name, HttpServletRequest request, JspWriter out) throws IOException{
        String currentUrl = request.getRequestURI();
        if (!StringUtils.isEmpty(request.getQueryString()))  {
            currentUrl = currentUrl + "?" + request.getQueryString();
        }
        if (!currentUrl.startsWith(url)) {
            out.print("<li><a href=\"" + url + "\">");
            out.print(name);
            out.print("</a></li>");
        } else {
            out.print("<li>");
            out.print(name);
            out.print("</li>");
        }
    }
    
    public void drawNode(MenuItem topItem, JspWriter out, HttpServletRequest request) throws IOException{
        if (topItem.getChildItems().size() > 0)   {
            out.print("<ul>");
            for (MenuItem item: topItem.getChildItems()) {
                if (item.getHidden()) {continue;}
                if (!StringUtils.isEmpty(item.getRedirectUrl())) {
                    drawLink(item.getRedirectUrl(), item.getName(), request, out);
                    drawNode(item, out, request);
                } else if (!StringUtils.isEmpty(item.getUrlString()) &&
                        item.getContentId() != null){
                    drawLink("/page/" + item.getUrlString(), item.getName(),request, out);
                    drawNode(item, out, request);
                } else if (item.getContentId() != null) {
                    drawLink("/page?key=" + item.getKey().getString(), item.getName(), request, out);
                    drawNode(item, out, request);
                }
            }
            out.print("</ul>");
        }

    }

%>


<%

    MenuService menuService = ((GuiService)request.getAttribute(ActionSupport.GUI_SERVICE)).getMenuService();
    menuService.setObjectify((Objectify)request.getAttribute(ActionSupport.OBJECTIFY));
    MenuItem top = menuService.getMenuItems();
    drawNode(top, out, request);


%>
